package com.gegong.imr.client.tasks.vmware;

import com.alibaba.fastjson.JSONObject;
import com.gegong.imr.client.IMessageClientProfiles;
import com.gegong.imr.client.bean.VmStatus;
import com.gegong.imr.client.config.ImrCenterConfig;
import com.gegong.imr.client.tasks.AbstractReportStatusTask;
import com.gegong.imr.client.tasks.CenterResponse;
import com.gegong.imr.client.tasks.TaskException;
import com.gegong.vmware.workstation.VMInformation;
import com.gegong.vmware.workstation.VirtualMachine;
import com.gegong.vmware.workstation.service.VMManagementService;
import com.gegong.vmware.workstation.service.VMNetworkAdaptersManagementService;
import com.gegong.vmware.workstation.service.VMPowerManagementService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
@Profile(IMessageClientProfiles.VMWARE)
public class VmwareReportStatusTask extends AbstractReportStatusTask {

    private final VMManagementService managementService;

    private final VMPowerManagementService powerManagementService;

    private ImrCenterConfig centerConfig;

    private final VMNetworkAdaptersManagementService networkAdaptersManagementService;

    @Autowired
    public VmwareReportStatusTask(VMManagementService managementService,
                                  VMPowerManagementService powerManagementService,
                                  ImrCenterConfig centerConfig,
                                  VMNetworkAdaptersManagementService networkAdaptersManagementService) {
        this.managementService = managementService;
        this.powerManagementService = powerManagementService;
        this.centerConfig = centerConfig;
        this.networkAdaptersManagementService = networkAdaptersManagementService;
    }

    @Override
    public void run() {
        String operation = "上报客户端状态";
        log.info(operation);
        try {
            List<VMInformation> informations = Lists.newArrayList();
            for (VirtualMachine vm : managementService.findAll()) {
                VMInformation information = VMInformation.builder().id(vm.getId()).vmxFilePath(vm.getPath()).build();
                information.setPowerState(powerManagementService.getPowerState(vm.getId()));
                information.setDevices(networkAdaptersManagementService.findAllNetworkAdapters(vm.getId()));
                informations.add(information);
            }

            List<VmStatus> clientStatuses = informations.stream().map(VmStatus::fromVmware).collect(Collectors.toList());

            RequestBody requestBody = RequestBody.create(defaultPostMediaType, JSONObject.toJSONString(clientStatuses));
            Request request = new Request.Builder()
                    .post(requestBody)
                    .headers(defaultHeaders)
                    .url(centerConfig.urlForReportClientStatus())
                    .build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw TaskException.forFailure(operation, response);
            assert response.body() != null;
            CenterResponse centerResponse = JSONObject.parseObject(response.body().string(), CenterResponse.class);
            if (!centerResponse.isSuccessful())
                throw TaskException.forBusiness(operation, centerResponse.getCode(), centerResponse.getMsg());
            log.info("客户端状态上报结果{}", centerResponse);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }


    }
}
